<template>
	<view class="page-bg">
		<u-navbar :border="false" :placeholder="true">
			<view slot="left"></view>
			<view slot="center" class="fb c3 f16">
				一键回收
			</view>
		</u-navbar>
		<scroll-view scroll-y="">
			<view class="item-bg mt10">
				<view class="c3 f16 fb ">
					物品品类
				</view>
				<view class="divider-line mt10 mb10" />
				<view class="f" style=" overflow-x: auto;white-space: nowrap;">
					<view class="f-f-c-c f14" style="width: 80px;"
						:class="[current==index?'select-item cm':'unselect-item c3']" v-for="item,index in options"
						:style="{marginLeft:index!=0?'20px':'0px'}" :key="index" @click="changeType(index)">
						<image :src="item.imgUrl" style="width: 80px;height: 60px;"></image>
						<view class="f14">
							{{item.name}}
						</view>
					</view>
				</view>
				<view
					style="display: grid;  grid-template-columns: 49% 49%;column-gap: 2%; row-gap: 10px; margin-top: 10px;"
					v-if="current==index" v-for="item,index in options" :key="index">
					<view class="f-s-b f14" :class="[currentItem==indexChild?'recycle-bg':'unrecycle-bg']"
						v-for="data,indexChild in item.childCategorizeVoList" :key="indexChild"
						@click="changeRecycle(indexChild)">
						<view class="ml10">
							{{data.name}}
						</view>
						<view class="mr10" v-if="data.priceType=='1'">
							可议价
						</view>
						<view class="mr10" v-else>
							{{data.price}}/{{data.unit}}
						</view>
					</view>
				</view>
				<view class="divider-line mt10 mb10"></view>
				<view class="sure-btn" style="width: 150px; margin: 0 auto;" @click="showAdd=true"> 添加</view>


			</view>

			<view class="item-bg mt10">
				<view class="c3 f16 fb ">
					已称重品类
				</view>
				<view class="divider-line mt10 mb10" />
				<view class="add-order" v-for="item,index in addItem" :key="index">
					<view>
						{{item.categorizeName}}
					</view>
					<view>
						{{item.weight}}{{item.unit}}
					</view>
					<view>
						￥{{item.totalPrice.toFixed(2)}}
					</view>
					<u-icon name="close-circle-fill" color="red" size="24" @click="deleteAdd(index)"></u-icon>

				</view>

			</view>
			<view class="item-bg p12 mt10">
				<view class="c3 fb f16 ">
					结算方式
				</view>
				<view class="divider-line mb10 mt10" />
				<u-radio-group v-model="payType" placement="row">
					<u-radio :customStyle="{marginBottom: '8px'}" v-for="(item, index) in radiolist1" :key="index"
						:label="item.label" :name="item.name">
					</u-radio>
				</u-radio-group>
			</view>
			<view class="item-bg p12 mt10" >
				<view class="c3 fb f16 ">
					支付凭证
				</view>
				<view class="divider-line mb10 mt10" />
				<view class="f-s-b f1 m15 pl10 pr10">
					<view style="width: 70px;height: 70px;" @click="uploadVochr">
						<image v-if="payImgUrl" :src="payImgUrl" style="width: 70px;height: 70px;">
						</image>
						<u-icon v-else name="photo" size="70"></u-icon>
					</view>
				</view>
			</view>

			<view class="f ml20 mr20 pb30" style="margin-top: 40px; margin-bottom: 60px;">
				<view class="sure-circle-btn f1" style="height: 44px;" @click="confirm">
					提交
				</view>
			</view>

		</scroll-view>
		<u-popup :round="10" :show="showAdd" mode="center" @close="closePop" :closeable="true">
			<view class="c3" style="width: 100vw;">
				<view class="f-f-c-c fb f18 mt10 mb10">
					添加
				</view>
				<view class="f ml10">
					<view>种类</view>
					<view class="input-bg f-s-b f1 m15">
						<uni-data-select v-model="currentItem" :localdata="list" :clear="false"></uni-data-select>
					</view>
				</view>
				<view class="f ml10">
					<view>单价</view>
					<view class="input-bg f-s-b f1 m15 pl10 pr10">
						<u-input :placeholder="placeValue"  v-model="price" border="none" @change="changePrice"
							:disabled="currentRecyc.priceType!='1'" />
						<view> 元</view>
					</view>
				</view>
				<view class="f ml10">
					<view v-show="currentRecyc.countType==0">重量</view>
					<view v-show="currentRecyc.countType==1">数量</view>

					<view class="input-bg f-s-b f1 m15 pl10 pr10">
						<u-input v-model="weight" @change="changeWeight" border="none"
							:disabled="disableIn=='0'"></u-input>
						<view>{{currentRecyc.unit}}</view>
					</view>
				</view>
				<view class="f ml10">
					<view>图片</view>
					<view class="f-s-b f1 m15 pl10 pr10">
						<view style="width: 70px;height: 70px;" @click="changeAvatar">
							<image v-if="recyclerImgUrl" :src="recyclerImgUrl" style="width: 70px;height: 70px;">
							</image>
							<u-icon v-else name="photo" size="70"></u-icon>
						</view>
					</view>
				</view>
				<view class="f ml10">
					<view>方式</view>
					<view class=" f-s-b f1 m15 pl10 pr10">
						<u-radio-group v-model="disableIn" placement="row" @change="typeChange">
							<u-radio label="自动输入" name="0">
							</u-radio>
							<u-radio :customStyle="{marginLeft: '8px'}" label="手动输入" name="1">
							</u-radio>
						</u-radio-group>
					</view>
				</view>

				<view class="sure-input f-f-c-c" @click="addRecycler">
					确认
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import * as config from '@/config'
	export default {


		data() {
			return {
				id: '',
				isConnectBlueTooth: false,
				showAdd: false,
				disableIn: '0',
				current: 0,
				currentItem: 0,
				currentItemValue: '',
				price: 0,
				weight: 0,
				totalPrice: 0,
				orderInfo: {},
				list: [],
				options: [],
				addItem: [],
				appointOrderId: '',
				placeValue: '',
				payImgUrl: '',
				recyclerImgUrl: '',
				radiolist1: [],
				// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
				payType: '1',
				isBlue: false,
				currentRecyc: {},

			}
		},
		onLoad(Option) {
			this.getInfo()
			this.getPayType()

		},
		onShow() {
			let that = this
			uni.getConnectedBluetoothDevices({
				fail(err) {
					uni.getStorage({
						key: 'blueTooth',
						success(res) {
							let data = JSON.parse(res.data)
							that.initBlue(data)
						},
						fail(refs) {
							that.isBlue = false
							that.disableIn = '1'
						}
					});
				},
				success(res) {
					console.log("链接成功" + res)
					if (res.devices.length > 0) {
						that.isConnectBlueTooth = true
						let data = {
							data: res.devices[0].name,
							deviceId: res.devices[0].deviceId
						}
						that.initService(data)
					}
				}
			})
		},

		methods: {
			getPayType() {
				let that = this
				that.request("get", "system/dict/data/type/pay_type", uni.getStorageSync('token'), null).then(
					res => {
						console.log(res)
						if (res.code === 200) {
							if (res.data.length > 0) {
								that.payType = res.data[0].dictValue
							}
							res.data.forEach(item => {
								that.radiolist1.push({
									name: item.dictValue + '',
									label: item.dictLabel
								})
							})
						}
					})
			},
			changeAvatar() {
				let that = this
				uni.chooseImage({

					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.uploadFile({
							url: config.def().baseUrl+'/oss/app/upload',//开发者服务器 url
							filePath: tempFilePaths[0],
							name: 'file',
							header: {
								'Authorization': 'Bearer ' + uni.getStorageSync('token')
							},
							success: (uploadFileRes) => {
								let data = JSON.parse(uploadFileRes.data)
								if (data.code == 200) {
									that.recyclerImgUrl = data.data.url
								}
							},
							fail: (res) => {
								console.log(res)
							}
						});
					}
				});

			},
			typeChange(n) {
				if (n == 0) {
					if (!this.isBlue) {
						uni.showToast({
							icon: 'error',
							title: '蓝牙未连接'
						})
					}
				}
			},
			uploadVochr() {
				let that = this
				uni.chooseImage({

					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.uploadFile({
							url: config.def().baseUrl+'/oss/app/upload',//开发者服务器 url
							filePath: tempFilePaths[0],
							name: 'file',
							header: {
								'Authorization': 'Bearer ' + uni.getStorageSync('token')
							},
							success: (uploadFileRes) => {
								let data = JSON.parse(uploadFileRes.data)
								if (data.code == 200) {
									that.payImgUrl = data.data.url
								}
							},
							fail: (res) => {
								console.log(res)
							}
						});

					}
				});
			},
			initMPService(data) {
				/**
				 * 获取所有服务
				 */
				console.log('获取所有服务的');
				let deviceId = data.deviceId;
				console.log('获取所有服务的 uuid:' + deviceId);
				uni.getBLEDeviceServices({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId,
					success: res => {
						console.log(JSON.stringify(res.services));
						console.log('获取设备服务成功:' + res.errMsg);
						this.list = res.services;

						this.characteristicsData = [];
						if (this.list.length <= 0) {
							toast('获取服务失败，请重试!');
							return;
						}
					},
					fail: e => {
						console.log('获取设备服务失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
			initService(data) {
				let that = this
				let deviceId = data.deviceId;
				console.log('初始化服务 deviceId' + deviceId);
				setTimeout(function() {
					// 连接成功后，获取该设备服务列表
					uni.getBLEDeviceServices({
						deviceId: deviceId,
						success(res) {
							res.services.forEach((item) => {
								console.log('遍历服务 ', JSON.stringify(item));
								let serviceId = item.uuid
								let flag = true
								// 寻找services下notify为true的特征id
								uni.getBLEDeviceCharacteristics({
									deviceId,
									serviceId,
									success: res => {
										console.log(serviceId, '找到特征 ', JSON.stringify(
											res));
										res.characteristics.forEach(item => {
											if (item.properties.notify &&
												flag) {
												that.domain.serviceId =
													serviceId
												that.domain
													.characteristicWatchId =
													item.uuid;
												that.domain.characteristicId =
													item.uuid;
												flag = false
												let dev = {
													data: data.name,
													deviceId: data
														.deviceId,
													serviceId: that.domain
														.serviceId,
													characteristicId: that
														.domain
														.characteristicWatchId,
												}
												console.log(
													"找到Service: ServiceId" +
													that.domain.serviceId)
												console.log(
													"找到Service: characteristicId" +
													that.domain
													.characteristicId)
												console.log("找到Service: dev" +
													dev)
												that
													.belNotifyBLECharacteristicValueChange(
														dev);
											}
										})
									},
									fail(res) {
										console.log('获取特征失败 ' + res);
									}
								});
							})

						},
						fail(res) {
							console.log('获取服务列表失败 ' + res);
						}
					})
				}, 1000)
			},
			initBlue(data) {
				let that = this
				uni.openBluetoothAdapter({
					// mode: 'cnetral',// 模式为 cnetral ，此处可不填写
					success(res) {
						console.log(res, '   res')
						that.createBLEConnection(data)
					},
					fail(res) {
						if (res.errMsg == 'openBluetoothAdapter:fail already opened') {
							that.createBLEConnection(data)
						} else {
							// 错误情况，弹出提示
							uni.showToast({
								icon: 'none',
								title: '未打开蓝牙'
							})
							that.isBlue = false
						}
					},
					complete(res) {}
				})
			},
			createBLEConnection(data) {
				console.log(data)
				let name = data.equipmentName
				let devId = data.deviceId
				let that = this
				uni.showLoading({
					title: '正在连接蓝牙...',
					mask: true
				})
				uni.createBLEConnection({
					deviceId: devId,
					success(res) {
						console.log(res)
						that.domain.deviceId = devId;
						// that.domain.serviceId = serviceId;
						that.domain.equipmentName = name;
						uni.hideLoading()
						uni.showToast({
							title: '连接成功',
						})
						setTimeout(function() {
							that.belNotifyBLECharacteristicValueChange(data)
						}, 2000)
					},
					fail(ress) {
						uni.hideLoading()
						if (ress.errMsg == 'createBLEConnection:fail already connect') {
							setTimeout(function() {
								that.belNotifyBLECharacteristicValueChange(data)
							}, 2000)
							uni.showToast({
								title: '连接成功',
							})
							return
						}
						uni.showToast({
							title: '连接失败错误码:' + ress.errCode + ' 请检查蓝牙状态',
						})
					}
				})
			},
			/**
			 {
			     "deviceId": "98:DA:60:0A:64:2C",
			     "serviceId": "0000FFE0-0000-1000-8000-00805F9B34FB",
			     "characteristicId": "0000FFE1-0000-1000-8000-00805F9B34FB"
			 }
**/
			belNotifyBLECharacteristicValueChange(data) {
				let that = this
				that.isBlue = true
				console.log(data)
				uni.notifyBLECharacteristicValueChange({
					deviceId: data.deviceId,
					serviceId: data.serviceId,
					characteristicId: data.characteristicId,
					state: true,
					success(res) {
						console.log(res, '   reaaa')
						uni.onBLECharacteristicValueChange(function(res1) {
							let readText = that.publicTools.ab2hex(res1.value)
							that.datastr = readText;
							if (that.disableIn == '0') {
								that.weight = that.datastr
							}
						})
					},
					fail: (res) => {
						console.log(res, '   222')
						uni.showToast({
							icon: 'none',
							title: '设备暂不支持接收数据',
							duration: 3000
						})
					}
				})
			},

			getInfo() {
				let that = this
				that.request("get", "categorize/app/allList", null, null).then(res => {
					if (res.code == 200) {
						that.options = res.data
						that.list = []
						that.price = that.options[that.current].childCategorizeVoList[that.currentItem].price
						that.currentRecyc = that.options[that.current].childCategorizeVoList[0]
						that.currentItemValue = that.currentRecyc.name
						let item = that.options[that.current].childCategorizeVoList;
						item.forEach(function(each) {
							that.list.push({
								text: each.name,
								value: item.indexOf(each)
							})
						})
					}
				})
			},
			navToView(url) {
				uni.navigateTo({
					url: url
				})
			},
			closeItem() {
				this.changeRecycle(this.currentItem)
			},
			close() {
				this.showAdd = false
			},

			closePop() {
				this.showAdd = false
				this.recyclerImgUrl = ''
			},
			changeType(value) {
				this.current = value
				this.changeRecycle(0)
			},
			changeRecycle(value) {
				this.currentItem = value
				this.list = []
				let item = this.options[this.current].childCategorizeVoList;
				let taht = this
				item.forEach(function(each) {
					taht.list.push({
						text: each.name,
						value: item.indexOf(each)
					})
				})
				this.currentRecyc = this.options[this.current].childCategorizeVoList[value]
				this.currentItemValue = this.currentRecyc.name
				if (this.currentRecyc.priceType == '1') {
					this.placeValue = "可议价"
					this.price = ""
					this.totalPrice = 0
				} else {
					this.placeValue = ""
					this.price = this.options[this.current].childCategorizeVoList[value].price
					this.totalPrice = this.price * this.weight
				}
			},
			changeWeight(e) {
				this.weight = e
				this.totalPrice = this.price * this.weight
			},
			changePrice(e) {
				this.price = e
				this.totalPrice = this.price * this.weight
			},
			deleteAdd(value) {
				console.log(value, ' delete')
				this.addItem.splice(value, 1)
			},
			deleteAll() {
				this.addItem = []
			},
			addRecycler() {
				if(!this.recyclerImgUrl){
					uni.showToast({
						icon: 'error',
						title: '请上传图片'
					})
					return
				}
				this.showAdd = false
				if (this.weight == 0) {
					return
				}
				let name = this.options[this.current].childCategorizeVoList[this.currentItem].name
				let item = this.options[this.current].childCategorizeVoList[this.currentItem]
				let ins=false
				let inItem
				this.addItem.forEach(it=>{
					if(it.categorizeId==item.id){
						ins=true
						inItem=it
					}
				})
				if(ins){
					this.addItem.forEach(it=>{
						if(it.categorizeId==inItem.categorizeId){
							it.price= this.price
							it.imgUrl= this.recyclerImgUrl
							it.weight= Number(it.weight)+ Number(this.weight)
							it.amount=  Number(it.price) * Number(it.weight)
							it.totalPrice=  Number(it.price) * Number(it.weight)
						}
					})
				}else{
					this.addItem.push({
						categorizeId: item.id,
						categorizeName: item.name,
						unit: item.unit,
						price: Number(this.price),
						imgUrl: this.recyclerImgUrl,
						amount: Number(this.price) * Number(this.weight),
						totalPrice: Number(this.price) * Number(this.weight),
						weight: Number(this.weight),
					})
				}
				this.recyclerImgUrl=''
				this.weight = 0
			},
			confirm() {
				let that = this
				let weightTal = 0
				let amountTal = 0
				that.addItem.map((it) => {
					weightTal += Number(it.weight)
					amountTal += Number(it.amount)
				})
				// if (that.payType != '4') {
				// 	if (that.payImgUrl.length == 0) {
				// 		uni.showToast({
				// 			title: '请上传支付凭证',
				// 			icon: 'error'
				// 		})
				// 		return
				// 	}
				// }
				let params = {
					appointOrderId: that.appointOrderId,
					weightTal: weightTal,
					amountTal: amountTal,
					hsUserWasteBoList: that.addItem,
					payType: that.payType,
					imgUrl: that.payImgUrl,
				}
				uni.showLoading({
					title: '提交中'
				})
				that.request("post", "riderAppOrder/app/addOneKeySettleOrder", uni.getStorageSync('token'),
					params).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						})
						that.deleteAll()
						that.appointOrderId = ''
						that.weightTal = 0
						that.amountTal = 0
						that.hsUserWasteBoList = []
						that.payType = '0'
						that.imgUrl = ''
						that.payImgUrl = ''
						that.recyclerImgUrl = ''
					}
					uni.hideLoading()
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	/deep/ .uni-select {
		border: none;
		width: 80vw;
	}

	.item-bg {
		padding: 12px;
		background: #FFFFFF;
		box-shadow: 0px 0px 4px 1px rgba(0, 0, 0, 0.1);
		border-radius: 4px 4px 4px 4px;
		opacity: 1;
	}

	.select-item {
		background: #FFFFFF;
		box-shadow: 0px 0px 4px 1px rgba(0, 0, 0, 0.1);
		border-radius: 4px 4px 4px 4px;
		opacity: 1;
		border: 1px solid #1AC388;
	}

	.unselect-item {
		background: #FFFFFF;
		box-shadow: 0px 0px 4px 1px rgba(0, 0, 0, 0.1);
		border-radius: 4px 4px 4px 4px;
		opacity: 1;
	}

	.recycle-bg {
		font-size: 14px;
		color: #1AC388;
		height: 34px;
		background: rgba(26, 195, 136, 0.24);
		border-radius: 4px 4px 4px 4px;
		border: 1px solid #1AC388;
	}

	.unrecycle-bg {
		font-size: 14px;
		color: #999999;
		height: 34px;
		background: rgba(255, 255, 255, 0.24);
		border-radius: 4px 4px 4px 4px;
		opacity: 1;
		border: 1px solid #CCCCCC;
	}

	.add-order {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 14px;
		color: #333333;
		margin: 10px auto;
		padding: 10px;
		background: rgba(204, 204, 204, 0.24);
		border-radius: 4px 4px 4px 4px;
		opacity: 1;
		border: 1px solid #CCCCCC;
	}

	.input-bg {
		height: 44px;
		background: #FAFAFA;
		border-radius: 4px 4px 4px 4px;
		border: 1px solid #E4E4E4;
	}



	.hand-input {
		width: 80%;
		margin: 10px auto;
		color: #1AC388;
		font-size: 16px;
		height: 44px;
		background: rgba(26, 195, 136, 0.1);
		border-radius: 22px 22px 22px 22px;
		border: 1px solid #1AC388;
	}

	.auto-input {
		width: 80%;
		margin: 10px auto;
		height: 44px;
		color: #1AC388;
		font-size: 16px;
		background: rgba(26, 195, 136, 0.1);
		border-radius: 22px 22px 22px 22px;
		border: 1px solid #1AC388;
	}

	.sure-input {
		width: 80%;
		margin: 10px auto;
		height: 44px;
		color: #FFFFFF;
		font-size: 16px;
		background: #1AC388;
		border-radius: 22px 22px 22px 22px;
		opacity: 1;
	}
</style>
